package liangzhi;

/**
 * @auther zhouliangliang
 * 三节点树节点
 * @date 2025/5/8 13:59
 * @description
 */
public class TreeNode<T> {
    private T data;
    private TreeNode<T> left;
    private TreeNode<T> right;

    private TreeNode<T> parent;

    public TreeNode(T data) {
        this.left = null;
        this.right = null;
        this.data = data;
    }

    public TreeNode(T data, TreeNode<T> left, TreeNode<T> right) {
        this.data = data;
        this.left = left;
        this.right = right;
    }

    public TreeNode(T data, TreeNode<T> left, TreeNode<T> right, TreeNode<T> parent) {
        this.data = data;
        this.left = left;
        this.right = right;
        this.parent = parent;
    }

    /**
     * 获取data
     * @return
     */
    public T getData() {
        return this.data;
    }

    /**
     * 设置data
     * @param data
     */
    public void setData(T data) {
        this.data = data;
    }

    /**
     * 获取left
     * @return
     */
    public TreeNode<T> getLeft() {
        return this.left;
    }

    /**
     * 设置left
     * @param left
     * @return
     */
    public void setLeft(TreeNode<T> left) {
        if(this.left != null) {
            this.left.parent = null;
        }
        this.left = left;
        if(left != null) {
            left.setParent(this);
        }
    }

    /**
     * 获取right
     * @return
     */
    public TreeNode<T> getRight() {
        return this.right;
    }

    public void setRight(TreeNode<T> right) {
        //更新现有节点的右子节点的parent为null
        if(this.right != null) {
            this.right.parent = null;
        }
        this.right = right;
        //设置现有节点的右子节点的parent
        if(right != null) {
            right.setParent(this);
        }
    }

    /**
     * 获取parent
     * @return
     */
    public TreeNode<T> getParent() {
        return this.parent;
    }

    /**
     * 设置parent
     * @return
     */
    public void setParent(TreeNode<T> parent) {
        this.parent = parent;
    }
}
